// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// f [author] rhyme_lph
// A [email]  rhymelph@gmail.com
// i [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/widgets/form/add_form.dart';
import 'package:finance_app/src/widgets/form/employee_contribution_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/number_form.dart';
import 'package:finance_app/src/widgets/form/text_currency_price_input_form.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:finance_app/src/widgets/select/normal_radio.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/hr_payroll/employee/views/employee_provider.dart';
import 'package:finance_app/src/provider/hr_payroll/employee/new_employee_provider.dart';
import 'package:tuple/tuple.dart';

class EmployeeView extends StatefulWidget {
  @override
  _EmployeeViewState createState() => _EmployeeViewState();
}

class _EmployeeViewState extends State<EmployeeView>
    with
        StatefulPresenter<EmployeeView, NewEmployeeProvider, EmployeeProvider>,
        KeepAliveMixin {
  @override
  Widget buildWidget(BuildContext context) => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            NormalFormWrapper(
              hasBottomBorder: true,
              topPadding: getDp(22),
              bottomPadding: getDp(24),
              child: listBuilder<String>(
                selector: (_, __) => __.currentSelectEmployeeType,
                builder: (BuildContext context, String value, Widget child) =>
                    Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [S.current.employee, S.current.company_director]
                      .map((e) => parentListBuilder<bool>(
                            selector: (_, __) => __.id == null
                                ? true
                                : __.isEdit &&
                                    Config.hasPermission(
                                        PermissionUtils.hrPayroll),
                            // &&
                            //     __.userId != null &&
                            //     Config.userProfile.id == __.userId,
                            builder: (BuildContext context, bool enable,
                                    Widget child) =>
                                PressedOpacityButton(
                              onPressed:
                                  (FormEditStatusInheritedWidget.ofEnable(
                                              context) &&
                                          enable)
                                      ? () {
                                          provider.onChangeEmployeeType(e);
                                        }
                                      : () {},
                              child: NormalRadio(
                                isEnable:
                                    FormEditStatusInheritedWidget.ofEnable(
                                            context) &&
                                        enable,
                                title: e,
                                isSelect: value == e,
                              ),
                            ),
                          ))
                      .toList(),
                ),
              ),
            ),
            parentListBuilder<bool>(
              selector: (_, __) => __.numberHasError,
              builder: (BuildContext context, bool value, Widget child) =>
                  FromInputField(
                hasError: value,
                controller: provider.employeeIdController,
                focusNode: provider.employeeIdFocusNode,
                tip: S.current.employee_id,
              ),
            ),
            FromInputField(
              controller: provider.jobTitleController,
              focusNode: provider.jobTitleFocusNode,
              tip: S.current.job_title,
            ),
            listBuilder<String>(
              selector: (_, __) => __.employmentType?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.employment_type,
                value: value,
                onTap: provider.onChangeEmploymentType,
              ),
            ),
            listBuilder<num>(
              selector: (_, __) => __.workingDaysCount,
              builder: (BuildContext context, num value, Widget child) =>
                  ValueSelectForm(
                title: S.current.no_of_working_days_per_week,
                value: value.toStringAsFixed(1),
                onTap: provider.onChangeWorkingDays,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => __.salaryPeriod?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.salary_period,
                value: value,
                onTap: provider.onChangeSalaryPeriod,
              ),
            ),
            listBuilder<List>(
              selector: (_, __) => List.from(__.salaryList),
              builder: (BuildContext context, List value, Widget child) =>
                  Column(
                children: List.generate(value.length, (index) {
                  final e = value[index];
                  if (index == 0) {
                    return TextCurrencyPriceInputForm(
                      controller: e['controller'],
                      focusNode: e['focusNode'],
                      currency: e['currency'],
                      title: e['title'],
                      onChangeCurrency: () => provider.onChangeUnit(e),
                    );
                  } else {
                    return ValueSelectForm(
                      title: e['title'] ?? '',
                      value: e['controller'].text,
                      onTap: () => provider.onSelectIncomeType(e),
                    );
                  }
                }),
              ),
            ),
            AddForm(
              title: S.current.add_income_type,
              onTap: provider.onAddIncomeType,
            ),
            parentListBuilder<bool>(
              selector: (_, __) => __.id == null || __.isEdit,
              builder: (BuildContext context, bool value, Widget child) =>
                  value ? AppSpaces.grayH05 : Container(),
            ),
            listBuilder<bool>(
                selector: (_, __) => __.isHideContribution,
                builder: (BuildContext context, bool value, Widget child) =>
                    Visibility(visible: !value, child: child),
                child: _buildSelfHelpGroup()),
            listBuilder<List<EmployeeContactDeductionData>>(
              selector: (_, __) => List.from(__.deductionList ?? []),
              builder: (BuildContext context,
                      List<EmployeeContactDeductionData> value, Widget child) =>
                  Column(
                children: value
                    .map((e) => ValueSelectForm(
                          title: e.name,
                          value: e.amount.toString(),
                          onTap: () => provider.onSelectFixedDeduction(e),
                        ))
                    .toList(),
              ),
            ),
            AddForm(
              title: S.current.add_fixed_deduction,
              onTap: provider.onAddFixedDeduction,
            ),
            AppSpaces.grayH6,
            listBuilder<String>(
              selector: (_, __) =>
                  DateTimeUtils.formatGlobalDateTime(__.hiredDate),
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.hired_date,
                value: value,
                onTap: provider.onChangeHiredDate,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) =>
                  DateTimeUtils.formatGlobalDateTime(__.confirmationDate),
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.confirmation_date,
                value: value,
                onTap: provider.onChangeConfirmationDate,
              ),
            ),
            listBuilder<List<EmployeeContactLeaveData>>(
              selector: (_, __) => List.from(__.leaveList ?? []),
              builder: (BuildContext context,
                      List<EmployeeContactLeaveData> value, Widget child) =>
                  Column(
                children: value
                    .map((e) => PressedOpacityButton(
                          onPressed: () =>
                              FormEditStatusInheritedWidget.ofEnable(context) ==
                                      true
                                  ? provider.onChangeLeaveType(e)
                                  : null,
                          child: NumberForm(
                            key: ValueKey(e.toJson()),
                            title: Config.settingData.leaveType
                                    .firstWhere(
                                        (element) => element.key == e.name,
                                        orElse: () => null)
                                    ?.name ??
                                '',
                            initialNumber: e.amount,
                            hasBottomBorder: true,
                            canZero: true,
                            disableHideButton: true,
                            onNumberCallback: (value) =>
                                provider.onChangeAnnualLeave(e, value),
                          ),
                        ))
                    .toList(),
              ),
            ),
            AddForm(
              title: S.current.add_leave_type,
              onTap: provider.onAddLeaveType,
            ),
            listBuilder<bool>(
              selector: (_, __) => __.isHideContribution,
              builder: (BuildContext context, bool value, Widget child) =>
                  Visibility(visible: value, child: child),
              child: Column(
                children: [
                  AppSpaces.grayH6,
                  TextCurrencyPriceInputForm(
                    controller: provider.foreignLevyController,
                    focusNode: provider.foreignLevyFocusNode,
                    // currency: "SGD",
                    title: S.current.foreign_worker_levy,
                    // onChangeCurrency: () => provider.onChangeUnit(e),
                  ),
                ],
              ),
            ),
            AppSpaces.h50,
          ],
        ),
      );

  Widget _buildSelfHelpGroup() {
    return listBuilder<Tuple2<String, double>>(
      selector: (_, __) => Tuple2(__.selfHelpGroup?.name, __.shgAmount),
      builder:
          (BuildContext context, Tuple2<String, double> value, Widget child) =>
              value.item1 == null
                  ? Column(
                      children: [
                        ValueSelectForm(
                          title: S.current.self_help_group,
                          onTap: provider.onChangeSelfHelpGroup,
                        ),
                        ValueSelectForm(
                          title: S.current.self_help_group_contribution,
                          onTap: provider.onChangeSelfHelpGroup,
                        )
                      ],
                    )
                  : PressedOpacityButton(
                      onPressed: provider.onChangeSelfHelpGroup,
                      child: EmployeeContributionForm(
                        shg: value?.item1,
                        amount: value?.item2,
                      ),
                    ),
    );
  }
}
